package com.appkubes.portal.admin.application.app.admin.service.impl;

import com.appkubes.common.exception.BusinessException;
import com.appkubes.portal.admin.application.app.admin.entity.vo.AdminAddVO;
import com.appkubes.portal.admin.application.app.admin.service.AppAdminService;
import com.appkubes.portal.admin.application.auth.service.KeyCloakUserService;
import org.keycloak.representations.idm.UserRepresentation;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class AppAdminServiceImpl implements AppAdminService {

    @Resource
    KeyCloakUserService keyCloakUserService;

    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public UserRepresentation save(AdminAddVO adminAddVO) {
        String adminKey = adminAddVO.getAdminKey();
        UserRepresentation createUserResult = null;
        String newPassword = adminAddVO.getPassword();
        //注册或更新用户
        if ((adminKey == null || "".equalsIgnoreCase(adminKey))) {
            //向sso授权服务中心注册该账号,并使用系统默认密码
            createUserResult = keyCloakUserService.createUser(adminAddVO.getUserName(), newPassword);
            return createUserResult;
        }

        //更新密码
        createUserResult = keyCloakUserService.getUserRepresentationById(adminKey);
        if (newPassword != null && !"".equalsIgnoreCase(newPassword)) {
            //如果密码不为空，则设置一下密码
            keyCloakUserService.resetPassword(adminKey, newPassword);
        }
        //设置用户状态
        Boolean enabled = adminAddVO.getEnabled();
        if (enabled != null) {
            keyCloakUserService.setEnable(adminKey, enabled);
        }


        return createUserResult;
    }
}
